package com.linwankaifa.linwancunyi.ui.login;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.DoctorBean;
import com.linwankaifa.linwancunyi.bean.PatientBean;
import com.linwankaifa.linwancunyi.util.Data_whole;
import com.linwankaifa.linwancunyi.util.JsonTransformation;
import com.linwankaifa.linwancunyi.util.Md5Util;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginRegister extends AppCompatActivity {
    EditText register_id;
    EditText register_password;
    EditText register_password_re;
    String SHAREDPREFERENCES_NAME = "shared.xml";
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        register_id = (EditText) findViewById(R.id.register_id);
        register_password = (EditText) findViewById(R.id.register_password);
        register_password_re = (EditText) findViewById(R.id.register_password_re);
    }

    public void registerBtn(View view) {
        if (!register_password.getText().toString().equals(register_password_re.getText().toString())) {
            Toast toast = Toast.makeText(getApplicationContext(), "两次输入的密码不一样", Toast.LENGTH_SHORT);
            toast.show();
            return;
        }
        if (register_id.getText().toString().isEmpty()) {
            Toast toast = Toast.makeText(getApplicationContext(), "账号不能为空", Toast.LENGTH_SHORT);
            toast.show();
        }

        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody = null;
        String id = register_id.getText().toString();
        String password = register_password.getText().toString();
        switch (preferences.getString("usertype", "")) {
            case "patient":
                PatientBean patient = new PatientBean();
                patient.setAccountnumber(id);
                patient.setPassword(Md5Util.StringInMd5(password));
                patient.setAllergens("未填写");
                patient.setBirthday("未填写");
                patient.setHeight(0);
                patient.setIsallergy("未填写");
                patient.setIsmarriage("未填写");
                patient.setPatientage(0);
                patient.setPatientname("未填写");
                patient.setPatientsex("未填写");
                patient.setPetname("未填写");
                patient.setPhone("未填写");
                patient.setWeight(0);
                requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                        JsonTransformation.objectToJson(patient));
                Log.e("dynamic", JsonTransformation.objectToJson(patient));
                break;
            case "doctor":
                DoctorBean doctor = new DoctorBean();
                doctor.setDoctoraccountnumber(id);
                doctor.setDoctorpassword(Md5Util.StringInMd5(password));
                doctor.setDoctorname("未填写");
                doctor.setDepartment("未填写");
                doctor.setDoctorage(0);
                doctor.setDoctorsex("未填写");
                doctor.setPosition("未填写");
                doctor.setSpeciality("未填写");
                requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                        JsonTransformation.objectToJson(doctor));
                Log.e("dynamic", JsonTransformation.objectToJson(doctor));
                break;
            default:
                Toast.makeText(getApplicationContext(), "不正确的角色", Toast.LENGTH_SHORT).show();
                break;

        }
        String url = getString(R.string.url)+"/";
        url += preferences.getString("usertype", "");
        url += "/insert";
        url += preferences.getString("usertype", "");
        switch (preferences.getString("usertype", "")) {
            case "patient":
                break;
            case "doctor":
                url += "info";
                break;
            default:
                break;
        }


        Log.e("dynamic", url);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast toast = Toast.makeText(getApplicationContext(), "返回失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        switch (isSuccess) {
                            case "404":
                                Log.e("dynamic", "why");
                                Toast.makeText(getApplicationContext(), "注册失败（可能已有该用户?）", Toast.LENGTH_SHORT).show();
                                return;
                            default:
                                switch (preferences.getString("usertype", "")) {
                                    case "patient":
                                        Data_whole.setPatientBean(JsonTransformation.jsonToObject(isSuccess, PatientBean.class));
                                        break;
                                    case "doctor":
                                        Data_whole.setDoctorBean(JsonTransformation.jsonToObject(isSuccess, DoctorBean.class));
                                        break;
                                    default:
                                        Toast.makeText(getApplicationContext(), "不正确的角色", Toast.LENGTH_SHORT).show();
                                        return;

                                }
                                Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                                LoginRegister.this.finish();
                                break;
                        }
                    }
                });

            }
        });
    }

    public void return_log(View view) {
        this.finish();
    }
}
